package com.zrb.mobile.register;

import org.apache.http.Header;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.LocationManagerProxy;
import com.amap.api.location.LocationProviderProxy;
import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.zrb.mobile.R;
import com.zrb.mobile.User_locationActivity;
import com.zrb.mobile.User_registerIndustry;
import com.zrb.mobile.adapter.model.RegisterDto;
import com.zrb.mobile.ui.fragment.NotifyFragment;
import com.zrb.mobile.utility.CommonUtil;
import com.zrb.mobile.utility.ZrbRestClient;

import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class BaseInfoFragment extends NotifyFragment implements OnClickListener ,AMapLocationListener {
	View RootView;
	TextView curAreaView,curIndustryView;
	EditText edtruename,edcompanyname,edjob;
	
	Button nextstep_btn;
    private LocationManagerProxy mLocationManagerProxy;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		// return inflater.inflate(R.layout.u_center_registerstep1, null);

		View view = inflater.inflate(R.layout.register_baseinfo, container, false);
		RootView=view;
 		initView();
		return view;
	}
	
	private void initView() {
  	 
		edtruename=(EditText)RootView.findViewById(R.id.edit_truename);
		edcompanyname=(EditText)RootView.findViewById(R.id.edit_companyname);
		edjob=(EditText)RootView.findViewById(R.id.edit_companyjob);
		
		RootView.findViewById(R.id.re_area).setOnClickListener(this);
		RootView.findViewById(R.id.re_trade).setOnClickListener(this);
		curAreaView=(TextView)RootView.findViewById(R.id.tv_area);
		curIndustryView=(TextView)RootView.findViewById(R.id.tv_trade);
		
		nextstep_btn=(Button)RootView.findViewById(R.id.nextbtn);
		nextstep_btn.setEnabled(true);
		nextstep_btn.setOnClickListener(this);
		
	}

	/**
	 * 初始化定位
	 */
	private void init() {
		// 初始化定位，只采用网络定位
		mLocationManagerProxy = LocationManagerProxy.getInstance(this.getActivity());
		mLocationManagerProxy.setGpsEnable(false);
		// 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
		// 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用removeUpdates()方法来取消定位请求
		// 在定位结束后，在合适的生命周期调用destroy()方法
		// 其中如果间隔时间为-1，则定位只定一次,
		// 在单次定位情况下，定位无论成功与否，都无需调用removeUpdates()方法移除请求，定位sdk内部会移除
		mLocationManagerProxy.requestLocationData(
				LocationProviderProxy.AMapNetwork, 60 * 1000, 15, this);
	}

	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		init();
		// mNewsItemDao = new NewsItemDao(getActivity());
	/*	avatarLoader = new LoadUserAvatar(getActivity());
		String avatar = LocalUserInfo.getInstance(getActivity()).getUseravatar();
		showUserAvatar(iv_avatar, avatar);
		// CommonUtil.showToast("results",
		// User_my_profiefragment.this.getActivity());
		LoadUserinfo();*/
	}

	
	private void saveStep1() {
		showloading("提交中...");
		RequestParams param = new RequestParams();

		param.put("phone", UserRegister.registerPhone);
		param.put("realname", edtruename.getText().toString());

		if (curAreaView.getTag() != null)
			param.put("locationId", curAreaView.getTag().toString());
		if (curIndustryView.getTag() != null) {
			param.put("industry", curIndustryView.getText());
			param.put("industryId", curIndustryView.getTag().toString());
		}

		param.put("org", edcompanyname.getText().toString());
		param.put("position", edjob.getText().toString());// 职务

		CommonUtil.InfoLog("saveUserInfoApiparam", param.toString());
		ZrbRestClient.post("register/saveUserInfoApi", param, new AsyncHttpResponseHandler() {

			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
				// TODO Auto-generated method stub
				hideloading();
				initNotify(BaseInfoFragment.this.getString(R.string.error_net_loadfail));
			}

			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				// TODO Auto-generated method stub
				hideloading(); 
				String results = new String(arg2);
				CommonUtil.InfoLog("saveUserInfoApi", results);
				try {
					Gson gson = new Gson();
					RegisterDto tmpDto = gson.fromJson(results, RegisterDto.class);
					if (tmpDto.res == 1) {
						Intent it5 = new Intent(BaseInfoFragment.this.getActivity(), UserRegisterFinish.class);
						it5.putExtra("phonenum", UserRegister.registerPhone);
						it5.putExtra("pwd", UserRegister.tmpsmsCode);
						startActivity(it5);
						BaseInfoFragment.this.getActivity().finish();
					} else  
						initNotify(tmpDto.msg);
					 
				} catch (Exception e) {
					initNotify(BaseInfoFragment.this.getString(R.string.error_serverdata_loadfail));

				}
			}
		});
	}
	
	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.re_area:
			Intent it6 = new Intent(this.getActivity(), User_locationActivity.class);
 			it6.putExtra("isucenter", true);
			this.startActivityForResult(it6, 105);
	 
 			break;
		case R.id.re_trade:
			Intent it5 = new Intent(this.getActivity(), User_registerIndustry.class);
			it5.putExtra("isProject", true);
			this.startActivityForResult(it5, 110);
 			break;
		case R.id.nextbtn:
 			saveStep1();
 			break;
		}
	}
	
 
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (resultCode == android.app.Activity.RESULT_OK) {
			switch (requestCode) {
 			case 110:// industry
				String industryname = data.getStringExtra("name");
				int industryCode = data.getIntExtra("code", -1);
				curIndustryView.setText(industryname);
				curIndustryView.setTag(industryCode);
				break;
 	 
			case 105:// tv_area
				String curArea = data.getStringExtra("area");
				String curCode = data.getStringExtra("code");
				CommonUtil.InfoLog("curArea", curArea + "");
				CommonUtil.InfoLog("curCode", curCode + "");
				curAreaView.setText(curArea);
 			 
				String areaCode=curCode.contains(",") ?curCode.split(",")[1]:curCode;
				curAreaView.setTag(areaCode);
				break;
	 
			}
			super.onActivityResult(requestCode, resultCode, data);
		}
	}
	
	
	@Override
	public void onPause() {
		super.onPause();
		if (mLocationManagerProxy != null) {
			// 移除定位请求
			mLocationManagerProxy.removeUpdates(this);
			// 销毁定位
			mLocationManagerProxy.destroy();
		}
	} 
	 
	 @Override
	public void onLocationChanged(Location location) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onLocationChanged(AMapLocation amapLocation) {
		// TODO Auto-generated method stub
		if (amapLocation != null && amapLocation.getAMapException().getErrorCode() == 0) {
			curAreaView.setText(amapLocation.getProvince() + " " + amapLocation.getCity());
			curAreaView.setTag(amapLocation.getAdCode().substring(0, 4) + "00"); 
			
	    }
   }
}
